﻿using SuporeSliplampApp.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using static SuporeSliplampApp.Util.Common;
using Newtonsoft.Json;
using FellowOakDicom.Network.Client;
using FellowOakDicom.Network;
using OpenCvSharp;
using System.Globalization;
using System.Security.Cryptography;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.Service;
using Supore.APP.UI.Controls.Notify;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// SettingView.xaml 的交互逻辑
    /// </summary>
    public partial class SettingView : UserControl
    {
        //dicom
        public delegate void GetIpInfoHandler(string ipStr);
        public GetIpInfoHandler getIpInfo;
        public Action<string> action;

        //print
        Common.Printinfo printinfo = new Common.Printinfo();

        //id
        public class IDSettings
        {
            public bool IsIDSwitchOn { get; set; }
            public string Patid { get; set; }
            public int PatidLength { get; set; }
        }
        private string patid;
        private string patLength;
        private bool isIDSwitchOn;

        //用户设置
        AddUserService service = new AddUserService();
        LoginService loginService = new LoginService();
        private UserModel _user;
        private int modeindex = 0;

        public SettingView()
        {
            InitializeComponent();
            init();

            //用户设置
            init2();
            List<UserModel> users = service.GetUsers();
            usersCombobox.SelectedItem = null;
            usersCombobox.ItemsSource = users;
            usersCombobox.DisplayMemberPath = "UserName";

            //打印设置
            if (File.Exists("printinfo.json"))
            {
                string json = File.ReadAllText("printinfo.json");
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Printinfo>(json);
                nameBox.Text = info.printname;
                adressBox.Text = info.printaddress;
                phoneBox.Text = info.printtelephone.ToString();
                logoBox.Text = info.logeimage;
            }

            //语言设置
            if (Common.languageCode == "zh-CN")
            {
                LanguageComboBox.SelectedIndex = 0;
            }
            else if (Common.languageCode == "en-US")
            {
                LanguageComboBox.SelectedIndex = 1;
            }

            //日期设置
            if (Common.DateIndex == 0)
            {
                DateComboBox.SelectedIndex = 0;
            }
            if (Common.DateIndex == 1)
            {
                DateComboBox.SelectedIndex = 1;
            }
            if (Common.DateIndex == 2)
            {
                DateComboBox.SelectedIndex = 2;
            }

        }

        //////////////////////////////////////////////
        ///

        private void init()
        {
            LoadIDSettings();
            ID.Text = patid;
            IDlength.Text = patLength;
            iDSwitch.IsOn = isIDSwitchOn;
        }

        private void init2()
        {
            Username_now.Clear();
            Password_now.Clear();
            Password_set.Clear();
            Password_re.Clear();
            Username_now.IsEnabled = true;
            userinfo.Visibility = Visibility.Hidden;
            Psw_now.Visibility = Visibility.Visible;
            Password_now.Visibility = Visibility.Visible;
            saveBtn.Visibility = Visibility.Hidden;
            cancelBtn.Visibility = Visibility.Hidden;
            usernewBtn.Visibility = Visibility.Visible;
            delBtn.Visibility = Visibility.Hidden;
            modeindex = 0;
        }

        private void UpgradeUserList()
        {
            List<UserModel> users = service.GetUsers();
            usersCombobox.SelectedItem = null;
            usersCombobox.ItemsSource = null;
            usersCombobox.ItemsSource = users;
            usersCombobox.DisplayMemberPath = "UserName";
        }

        //打印
        private void OpenPath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "图片|*.jpg;*.jpeg;*.bmp;*.png;*.mp4"
            };
            if (openFileDialog.ShowDialog() == true)
            {
                logoBox.Text = openFileDialog.FileName;
            }
        }
        private void SaveBtn_Click(Object sender, RoutedEventArgs e)
        {
            try
            {
                printinfo.printname = nameBox.Text;
                printinfo.printaddress = adressBox.Text;
                printinfo.printtelephone = phoneBox.Text;
                printinfo.logeimage = logoBox.Text;

                string json = Newtonsoft.Json.JsonConvert.SerializeObject(printinfo, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText("printinfo.json", json);
            }
            catch { }
            if (File.Exists("printinfo.json"))
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageView messageView = new MessageView("保存成功!", 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
                else
                {
                    MessageView messageView = new MessageView("Save Successful!", 0);
                    messageView.Owner = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>().FirstOrDefault(w => w.IsActive);
                    messageView.ShowDialog();
                }
            }
        }

        //语言设置
        private void LanguageComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedLanguage = (ComboBoxItem)LanguageComboBox.SelectedItem;
            string languageCode = selectedLanguage.Tag.ToString();

            try
            {
                switch (languageCode)
                {
                    case "zh-CN":
                        string chinese = "pack://application:,,,/Resource/zh-CN.xaml";
                        Application.Current.Resources.MergedDictionaries[3].Source = new Uri(chinese);
                        Common.languageCode = "zh-CN";
                        break;
                    case "en-US":
                        string english = "pack://application:,,,/Resource/en-US.xaml";
                        Application.Current.Resources.MergedDictionaries[3].Source = new Uri(english);
                        Common.languageCode = "en-US";
                        break;
                    default:
                        string Default = "pack://application:,,,/Resource/zh-CN.xaml";
                        Application.Current.Resources.MergedDictionaries[3].Source = new Uri(Default);
                        Common.languageCode = "zh-CN";
                        break;
                }

                var settings = new { LanguageCode = languageCode };
                string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
                File.WriteAllText("LanguageSettings.json", json);
            }
            catch (IOException ex)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("数据保存失败");
                }
                else
                {
                    MessageBox.Show("Failed!");
                }
            }
            catch (Exception ex)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("数据保存失败");
                }
                else
                {
                    MessageBox.Show("Failed!");
                }
            }
        }

        //日期设置
        private void Date_selected(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                Common.DateIndex = DateComboBox.SelectedIndex;
                var settings = new { DateCode = DateComboBox.SelectedIndex };
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(settings, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText("DateSettings.json", json);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        //DICOM设置
        private void sendData()
        {
            this.action?.Invoke(IpStr.Text.ToString().Trim() + ":" + PortStr.Text.ToString().Trim());
        }
        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Keyboard.ClearFocus();
        }
        private async void DCMConfirmBtn_Click(object sender, RoutedEventArgs e)
        {
            string ip = IpStr.Text.Trim();
            int port = int.Parse(PortStr.Text.Trim());

            var currentClient = DicomConnectionManager.Instance.GetClient();
            if (currentClient != null)
            {
                MessageBox.Show($"已经连接到 {ip}:{port} 的服务器！");
                return;
            }

            bool isConnected = await DicomConnectionManager.Instance.Connect(ip, port);
            if (isConnected)
            {
                var dicomClient = DicomConnectionManager.Instance.GetClient();
                var echoRequest = new DicomCEchoRequest();
                echoRequest.OnResponseReceived += (req, response) =>
                {
                    if (response.Status == DicomStatus.Success)
                    {
                        MessageBox.Show("连接成功！可以正常通信。");
                    }
                    else
                    {
                        MessageBox.Show("连接成功，但服务器未能正确响应C-ECHO请求。");
                    }
                };

                await dicomClient.AddRequestAsync(echoRequest);
                await dicomClient.SendAsync();

            }
            else
            {
                MessageBox.Show("连接失败，请检查IP和端口号。");
            }
        }

        private async void DCMTestBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var testClient = DicomClientFactory.Create(IpStr.Text.Trim(), int.Parse(PortStr.Text.Trim()), false, "SCU", "ORTHANC");
                var request = new DicomCEchoRequest();

                request.OnResponseReceived += (req, response) =>
                {
                    if (response.Status == DicomStatus.Success)
                    {
                        MessageBox.Show("测试连接成功！");
                    }
                    else
                    {
                        MessageBox.Show($"测试连接失败: {response.Status.Description}");
                    }
                };

                await testClient.AddRequestAsync(request);
                await testClient.SendAsync();

                testClient = null;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"测试连接失败: {ex.Message}");
            }
        }

        //ID设置
        private void IDlength_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textBox = (TextBox)sender;

            if (string.IsNullOrWhiteSpace(textBox.Text) || textBox.Text == "0")
            {
                textBox.Text = "1";
            }
            else
            {
                int number;
                bool isNumeric = int.TryParse(textBox.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out number);

                if (!isNumeric)
                {
                    textBox.Text = "1";
                }
                else
                {
                    if (number < 1)
                    {
                        textBox.Text = "1";
                    }
                    else if (number > 10)
                    {
                        textBox.Text = "10";
                    }
                }
            }
            textBox.CaretIndex = textBox.Text.Length;
        }

        private void IDAdd_Click(object sender, RoutedEventArgs e)
        {
            int currentNumber;
            if (int.TryParse(IDlength.Text, out currentNumber))
            {
                currentNumber = Math.Min(10, currentNumber + 1);
                IDlength.Text = currentNumber.ToString();
            }
        }
        private void IDDec_Click(object sender, RoutedEventArgs e)
        {
            int currentNumber;
            if (int.TryParse(IDlength.Text, out currentNumber))
            {
                currentNumber = Math.Max(1, currentNumber - 1);
                IDlength.Text = currentNumber.ToString();
            }
        }
        private void SaveIDSettings()
        {
            try
            {
                var iDSettings = new IDSettings();
                iDSettings.IsIDSwitchOn = iDSwitch.IsOn;
                if (iDSwitch.IsOn)
                {
                    iDSettings.Patid = ID.Text;
                    iDSettings.PatidLength = int.Parse(IDlength.Text);
                }
                else
                {
                    iDSettings.Patid = patid;
                    iDSettings.PatidLength = int.Parse(patLength);
                }

                string json = JsonConvert.SerializeObject(iDSettings, Formatting.Indented);
                File.WriteAllText("idsettings.json", json);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void LoadIDSettings()
        {
            if (File.Exists("idsettings.json"))
            {
                string json = File.ReadAllText("idsettings.json");
                var idsettings = JsonConvert.DeserializeObject<IDSettings>(json);

                patid = idsettings.Patid;
                patLength = idsettings.PatidLength.ToString();
                isIDSwitchOn = idsettings.IsIDSwitchOn;
            }
        }
        private void IDon_Click(object sender, RoutedEventArgs e)
        {
            SaveIDSettings();

            if (Common.languageCode == "zh-CN")
            {
                MessageView messageView = new MessageView("设置成功!", 0);
                messageView.Owner = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>().FirstOrDefault(w => w.IsActive);
                messageView.ShowDialog();
            }
            else
            {
                MessageView messageView = new MessageView("Setting Saved!", 0);
                messageView.Owner = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>().FirstOrDefault(w => w.IsActive);
                messageView.ShowDialog();
            }

        }

        //用户设置

        private void UserComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserModel selectedUser = usersCombobox.SelectedItem as UserModel;
            if (selectedUser != null)
            {
                userinfo.Visibility = Visibility.Visible;
                Username_now.Text = selectedUser.UserName;
                isAdmin.IsOn = selectedUser.IsAdmin == 1;
                Username_now.IsEnabled = false;
                Psw_now.Visibility = Visibility.Visible;
                Password_now.Visibility = Visibility.Visible;
                saveBtn.Visibility = Visibility.Visible;
                cancelBtn.Visibility = Visibility.Visible;
                delBtn.Visibility = Visibility.Visible;
                usernewBtn.Visibility = Visibility.Hidden;
                modeindex = 2;
            }
        }

        private void NewUser_Click(object sender, RoutedEventArgs e)
        {
            if (modeindex == 1)
            {
                Username_now.Clear();
                Password_now.Clear();
                Password_set.Clear();
                Password_re.Clear();
                isAdmin.IsOn = false;
            }
            modeindex = 1;
            userinfo.Visibility = Visibility.Visible;
            Psw_now.Visibility = Visibility.Hidden;
            Password_now.Visibility = Visibility.Hidden;
            saveBtn.Visibility = Visibility.Visible;
            cancelBtn.Visibility = Visibility.Visible;
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            Username_now.Clear();
            Password_now.Clear();
            Password_set.Clear();
            Password_re.Clear();
            isAdmin.IsOn = false;
        }

        private void Del_Click(object sender, RoutedEventArgs e)
        {
            _user = new UserModel();
            _user.UserName = Username_now.Text.Trim();
            if (!service.DeleteUser(_user))
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("删除失败！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Deletion Failed!");
                }
                //LayUINotify.ShowInfo("删除失败！");
                return;
            }
            else
            {
                if (Common.languageCode == "zh-CN")
                {
                    LayUINotify.ShowInfo("删除成功！");
                }
                else
                {
                    LayUINotify.ShowInfo("Tip", "Deletion Successful!");
                }

                if (File.Exists("usernames.json"))
                {
                    var jsonContent = File.ReadAllText("usernames.json");
                    var dataList = JsonConvert.DeserializeObject<List<string>>(jsonContent);
                    if (dataList != null)
                    {
                        if (dataList.Remove(_user.UserName))
                        {
                            File.WriteAllText("usernames.json", JsonConvert.SerializeObject(dataList, Formatting.Indented));
                        }
                    }


                }

                UpgradeUserList();
                init2();
                return;
            }

        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
             UpgradeUserList();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            init2();
            Username_now.IsEnabled = true;
            Psw_now.Visibility = Visibility.Visible;
            Password_now.Visibility = Visibility.Visible;
            delBtn.Visibility = Visibility.Hidden;
            usernewBtn.Visibility = Visibility.Visible;
            Username_now.Clear();
            Password_now.Clear();
            Password_set.Clear();
            Password_re.Clear();
            isAdmin.IsOn = false;

            usersCombobox.SelectedItem = null;
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (modeindex == 1)
            {
                if (Password_set.Password.Trim() != Password_re.Password.Trim())
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        MessageBox.Show("两次密码输入不一致，请重新输入!", "提醒");
                    }
                    else
                    {
                        MessageBox.Show("Passwords do not match. Please re-enter.!", "Tip");
                    }
                    //MessageBox.Show("两次密码输入不一致，请重新输入!", "提醒");
                    Password_set.Clear();
                    Password_re.Clear();
                    return;
                }

                _user = new UserModel();

                _user.UserName = this.Username_now.Text.Trim();
                _user.Password = this.Password_set.Password.Trim();

                if (this.isAdmin.IsOn)
                {
                    _user.IsAdmin = 1;
                }
                else
                {
                    _user.IsAdmin = 0;
                }

                if (!service.AddUser(_user))
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        LayUINotify.ShowInfo("注册失败！");
                    }
                    else
                    {
                        LayUINotify.ShowInfo("Tip", "Registration Failed!");
                    }
                    //LayUINotify.ShowInfo("注册失败！");
                    return;
                }
                else
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        LayUINotify.ShowSuccess("注册成功！");
                    }
                    else
                    {
                        LayUINotify.ShowSuccess("Tip", "Registration Successful!");
                    }
                    //LayUINotify.ShowSuccess("注册成功！");
                    UpgradeUserList();
                    init2();
                    return;
                }
            }

            if (modeindex == 2)
            {
                if (!loginService.CheckLogin(Username_now.Text.ToString(), Password_now.Password.ToString()))
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        LayUINotify.ShowInfo("用户名或密码不正确");
                    }
                    else
                    {
                        LayUINotify.ShowInfo("Tip", "Username or Password Incorrect");
                    }
                    //LayUINotify.ShowInfo("用户名或密码不正确");
                    return;
                }
                else
                {
                    if (Password_set.Password.Trim() != Password_re.Password.Trim())
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            MessageBox.Show("两次密码输入不一致，请重新输入!", "提醒");
                        }
                        else
                        {
                            MessageBox.Show("Passwords do not match. Please re-enter!", "Tip");
                        }
                        //MessageBox.Show("两次密码输入不一致，请重新输入!", "提醒");
                        Password_set.Clear();
                        Password_re.Clear();
                        return;
                    }
                    _user = new UserModel();

                    _user.UserName = this.Username_now.Text.Trim();
                    _user.Password = this.Password_set.Password.Trim();

                    if (this.isAdmin.IsOn)
                    {
                        _user.IsAdmin = 1;
                    }
                    else
                    {
                        _user.IsAdmin = 0;
                    }

                    if (!service.UpdateUser(_user))
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            LayUINotify.ShowInfo("修改失败！");
                        }
                        else
                        {
                            LayUINotify.ShowInfo("Tip", "Modification Failed!");
                        }
                        //LayUINotify.ShowInfo("修改失败！");
                        return;
                    }
                    else
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            LayUINotify.ShowSuccess("修改成功！");
                        }
                        else
                        {
                            LayUINotify.ShowSuccess("Tip", "Modification Successful!");
                        }
                        //LayUINotify.ShowSuccess("修改成功！");
                        UpgradeUserList();
                        init2();
                        return;
                    }
                }
            }
        }
    }


    public class DicomConnectionManager
    {
        private static DicomConnectionManager _instance;
        private IDicomClient _dicomClient;

        private DicomConnectionManager() { }

        public static DicomConnectionManager Instance => _instance ?? (_instance = new DicomConnectionManager());

        public async Task<bool> Connect(string ip, int port)
        {
            try
            {
                _dicomClient = DicomClientFactory.Create(ip, port, false, "SCU", "ORTHANC");
                var request = new DicomCEchoRequest();
                await _dicomClient.AddRequestAsync(request);
                await _dicomClient.SendAsync();
                return true;
            }
            catch
            {
                _dicomClient = null;
                return false;
            }
        }

        public IDicomClient GetClient()
        {
            return _dicomClient;
        }

        public void Disconnect()
        {
            if (_dicomClient != null)
            {
                _dicomClient = null;
            }
        }
    }




}
